package com.navidove.commons.utils;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringUtils;

import com.navidove.commons.vo.EnhanceEnum;

@SuppressWarnings("rawtypes")
public class EnhanceEnumPropertyEditor extends PropertyEditorSupport {
    
    private Class<? extends Enum> clazz;
    public EnhanceEnumPropertyEditor(Class<? extends Enum> clazz) {
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isBlank(text)){
            return;
        }
        
        if (EnhanceEnum.class.isAssignableFrom(clazz)) {
            for (Enum e : clazz.getEnumConstants()) {
                if (text.equals(((EnhanceEnum) e).getCode())) {
                    setValue(e);
                    break;
                }
            }
        }
        
        if (getValue() == null) {
            setValue(Enum.valueOf(clazz, text));
        }
    }

    /**
     * @see java.beans.PropertyEditorSupport#getAsText()
     */
    public String getAsText() {
        Object value = getValue();
        if (value == null)
            return null;
        try {
            if (value instanceof EnhanceEnum) {
                return ((EnhanceEnum) value).getCode();
            }
        	return value.toString();
        } catch (Exception e) {
        	//throw new IllegalStateException(e);
        }
        return null;
    }
}
